import request from '@/utils/request'
import { AppThunk } from '../index'
import {
  setChannel,
  getrestChannel,
  delChannelList,
  addChannelList,
} from '../modules/channels'
import _ from 'lodash'
import { Channel, UserChannelResponse } from '@/types/data'
// 3. 异步action
export const getChanenlList = (payload?: unknown): AppThunk => {
  return async (dispatch, getState) => {
    const res = await request.get('/user/channels')
    // console.log(res)
    dispatch(setChannel(res.data.channels))
  }
}
//全部列表
export const getAllChanenlList = (): AppThunk => {
  return async (dispatch, getState) => {
    const res: UserChannelResponse = await request.get('/channels')
    // console.log(res.data.channels)
    const { channels } = getState().channels
    const restList = _.differenceBy(res.data.channels, channels, 'id')
    // console.log(restList)
    dispatch(getrestChannel(restList))
  }
}
// 删除
export const delChannel = (channel: Channel): AppThunk => {
  return async (dispatch, getState) => {
    await request.delete(`/user/channels/${channel.id}`)

    dispatch(delChannelList(channel))
  }
}
// 添加
export const addChannel = (channel: Channel): AppThunk => {
  return async (dispatch, getState) => {
    await request.patch(`/user/channels`, {
      channels: [{ id: channel.id, seq: channel.id }],
    })

    dispatch(addChannelList(channel))
  }
}
